package com.mp.netty.controller;

import com.mp.core.utils.JsonUtils;
import com.mp.core.utils.MrdNettyResult;
import com.mp.core.utils.common.NettyCommon;
import com.mp.enums.ActionEnum;
import com.mp.netty.manage.WebsiteFlyRecordManage;
import com.mp.pojo.NO.DataContentNO;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * TestController class
 *
 * @author BuK
 * @date 2019/05/28
 */
@Component
public class NettyController {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private NettyCommon nettyCommon;

    @Autowired
    private WebsiteFlyRecordManage websiteFlyRecordManage;

    /**
     * 获取用户传输的数据并且转化为对象
     *
     * @param msg
     * @param userChannel
     * @return
     */
    public DataContentNO getDataContent(TextWebSocketFrame msg, Channel userChannel) {
        // 获取客户端传输过来的消息
        String content = msg.text();
        // 1. 获取客户端发来的消息
        DataContentNO dataContent = null;
        System.out.println("##############msg##############");
        System.out.println(content);
        System.out.println("##############msg##############");

        try {
            dataContent = JsonUtils.jsonToPojo(content, DataContentNO.class);
            return dataContent;
        } catch (Exception e) {
            System.out.println("##############数据##############");
            System.out.println(content);
            System.out.println("##############数据##############");
            logger.info("channelId: " + userChannel.id().asShortText() + " : 请完善参数");
            //ws通知
            nettyCommon.wsSimpleWrite(userChannel, MrdNettyResult.convertError("请完善参数", ActionEnum.ERROR));
            return dataContent;
        }
    }


    /**
     * 飞单记录
     * @param dataContent
     */
    public void flyRecord(DataContentNO dataContent) {
        websiteFlyRecordManage.flyRecord(dataContent.getFlyRecord());
    }

    /**
     * 绑定Channel
     * @param dataContent
     * @param channel
     */
    public void binDingChannel(DataContentNO dataContent, Channel channel) {
        websiteFlyRecordManage.binDingChannel(dataContent.getBinDingChannel(),channel);
    }
}
